import { REQU, SignInInfoInvalidCondPair, toFormData, useResp } from "@/net/requ";
import { message } from "ant-design-vue";
import * as storage from '@/util/storage.js';
import { UUID } from "@/util/rnd";
import { strToArr } from "@/util";

export const SerialNumClassName = R.prop(R.__, { 1: 'pass', 2: 'reject' });

export function storePkgInfo(ques) {
  const pkgInfo = R.mergeRight(storage.readAsObj('pkgInfo'), { ques: ques.assignedFileId });
  storage.writeAsStr('pkgInfo', pkgInfo);
}

export function LabelFromStorableOf({ classes, labelColorDic }) {
  return function LabelFromStorable() {
    return function(layer) {
      const action = classes.value[layer.action];
      const color = labelColorDic.value[action];
      return Object.assign( layer, { action, color } );
    }
  }
}

export function SrcFromStorableOf({ srcs }) {
  return function SrcFromStorable(ques, quesIndex) {
    return R.prop(quesIndex, srcs.value);
  }
}

export function CustomToQues(transformerMap) {
  const DefaultAnnotation = (ques, quesIndex) => ({
    video: {
      filename: UUID(),
      src: transformerMap.Src(ques, quesIndex),
      fps: 10,
      frames: void 0,
      duration: void 0,
      height: void 0,
      width: void 0
    },
    actionAnnotationList: []
  });

  const assignAnnotation = target => Object.assign(
    target,
    {
      annotation: {
        video: target.annotation.video,
        actionAnnotationList: target.annotation.actionAnnotationList.map(transformerMap.Label())
      }
    }
  );

  const AssignedLabels = (ques, quesIndex) => R.ifElse(
    R.identity,
    assignAnnotation,
    R.always({ annotation: DefaultAnnotation(ques, quesIndex) })
  );

  /** 添加对题保存、标注和审核等必需的字段 */
  return function Ques(file, fileIndex) {
    return Object.assign(file, {
      assignedLabels: R.compose( AssignedLabels(file, fileIndex), R.curryN(1, JSON.parse) )(file.assignedLabels),
      assignedFileId: file.id,
      comments: strToArr(R.curryN(1, JSON.parse))(file.note),
    });
  }
}

export function CustomSaveFile(opts) {
  /** @param {ImgSegmnt.Ques} ques */
  return function saveFile(ques) {
    if (!opts.cond()) { return Promise.resolve('不满足保存条件'); }

    opts.pre(ques);

    return REQU('/api/task/assignedFileSave', {
      method: 'POST',
      body: toFormData(opts.Params(ques)),
    })
    .then(useResp({
      succ: R.identity,
      fail: R.cond([
        SignInInfoInvalidCondPair(),
        [
          R.T,
          R.pipe(
            R.tap(R.both( R.prop('message'), R.tap(message.error) )),
            R.compose( R.tap(console.log), opts.Msg ),
            R.compose( R.tap(message.error), opts.Msg ),
          )
        ],
      ]),
    }))
  }
}
